"use client";

import { ReactNode, RefObject, useEffect, useImperativeHandle, useRef } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";

import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { ColorPicker } from "@/components/ui/color-picker";
import { ResumeIcon } from "@/components/ui/resume-icon";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { resumeFormSchema, type Resume } from "@/lib/schemas/resume-form";
import { chunk } from "@/lib/utils";

// 表单卡片组件
function FormCard({ title, children }: { title: string; children: ReactNode }) {
  return (
    <Card className="mb-6">
      <CardHeader>
        <CardTitle className="text-lg">{title}</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">{children}</CardContent>
    </Card>
  );
}

interface ResumeFormProps {
  value?: Resume;
  onChange?: (value: Resume) => void;
  ref?: RefObject<ResumeFormRef | null>;
}

export type ResumeFormRef ={ reset: (value: Resume) => void, getValues: () => Resume };

export default function ResumeForm({ value, onChange, ref }: ResumeFormProps) {
  const bodyLeftRef = useRef<HTMLDivElement>(null);

  const form = useForm<Resume>({
    resolver: zodResolver(resumeFormSchema),
    defaultValues: value,
  });
    
    

  useImperativeHandle(ref, () => {
    return {
      reset: (value: Resume) => {
        form.reset(value);
        },
        getValues: () => {
          return form.getValues();
        },
    };
  });

  // 当value变化时，重置表单
  //   React.useEffect(() => {
  //     if (value) {
  //       form.reset(value);
  //     }
  //   }, [form]);

  //   // 监听表单数据变化，通知父组件
  useEffect(() => {
    const subscription = form.watch((value) => {
      if (onChange && value) {
        onChange(value as Resume);
        // form.reset(value);
      }
    });
    return () => subscription.unsubscribe();
  }, [form, onChange]);

  const {
    fields: basicInfoFields,
    append: appendBasicInfo,
    remove: removeBasicInfo,
  } = useFieldArray({
    control: form.control,
    name: "basicInfo.data",
  });

  const {
    fields: educationFields,
    append: appendEducation,
    remove: removeEducation,
  } = useFieldArray({
    control: form.control,
    name: "education.data",
  });

  const {
    fields: experienceFields,
    append: appendExperience,
    remove: removeExperience,
  } = useFieldArray({
    control: form.control,
    name: "experience.data",
  });

  const {
    fields: externalsFields,
    append: appendExternal,
    remove: removeExternal,
  } = useFieldArray({
    control: form.control,
    name: "externals",
  });

  function onSubmit(values: Resume) {
    console.log(values);
  }

  return (
    <div className="resume-detail-page-body-left" ref={bodyLeftRef}>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          {/* 头像字段（隐藏） */}
          <FormField
            control={form.control}
            name="avatar"
            render={({ field }) => (
              <FormItem className="hidden">
                <FormControl>
                  <Input {...field} />
                </FormControl>
              </FormItem>
            )}
          />

          {/* 简历信息 */}
          <FormCard title="简历信息">
            <FormField
              control={form.control}
              name="title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>简历标题</FormLabel>
                  <FormControl>
                    <Input placeholder="请输入简历标题" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="primary"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>主题色</FormLabel>
                    <FormControl>
                      <ColorPicker
                        showText
                        {...field}
                        onChange={(e) => field.onChange(e.target.value)}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="secondary"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>次级色</FormLabel>
                    <FormControl>
                      <ColorPicker
                        showText
                        {...field}
                        onChange={(e) => field.onChange(e.target.value)}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </FormCard>

          {/* 基础信息 */}
          <FormCard title="基础信息">
            <FormField
              control={form.control}
              name="basicInfo.title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>标题</FormLabel>
                  <FormControl>
                    <Input placeholder="请输入标题" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {chunk(basicInfoFields, 2).map((subList, subIndex) => (
              <div key={subIndex} className="grid grid-cols-2 gap-4">
                {subList.map((item, index) => {
                  const actualIndex = subIndex * 2 + index;
                  return (
                    <div key={item.id} className="space-y-2">
                      <div className="flex gap-2">
                        <FormField
                          control={form.control}
                          name={`basicInfo.data.${actualIndex}.label`}
                          render={({ field }) => (
                            <FormItem className="flex-1">
                              <FormControl>
                                <Input placeholder="标签" {...field} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                        <FormField
                          control={form.control}
                          name={`basicInfo.data.${actualIndex}.val`}
                          render={({ field }) => (
                            <FormItem className="flex-1">
                              <FormControl>
                                <Input placeholder="值" {...field} />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                        <Button
                          type="button"
                          variant="outline"
                          size="icon"
                          onClick={() => removeBasicInfo(actualIndex)}
                          className="h-9 w-9"
                        >
                          <ResumeIcon icon="ie-stick" size={14} />
                        </Button>
                      </div>
                    </div>
                  );
                })}
              </div>
            ))}

            <Button
              type="button"
              variant="outline"
              onClick={() => appendBasicInfo({ label: "", val: "" })}
              className="w-full"
            >
              <ResumeIcon icon="plus" size={16} className="mr-2" />
              添加基础信息项
            </Button>
          </FormCard>

          {/* 教育经历 */}
          <FormCard title="教育经历">
            <FormField
              control={form.control}
              name="education.title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>标题</FormLabel>
                  <FormControl>
                    <Input placeholder="请输入标题" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {educationFields.map((item, index) => {
              const school = form
                .watch(`education.data.${index}.school`)
                ?.trim();
              const program = form
                .watch(`education.data.${index}.program`)
                ?.trim();
              const title =
                [school, program].filter(Boolean).join(" / ") ||
                `教育经历 ${index + 1}`;

              return (
                <Card key={item.id} className="border-dashed">
                  <CardHeader>
                    <CardTitle className="text-base">{title}</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <FormField
                      control={form.control}
                      name={`education.data.${index}.school`}
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>学校</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入学校名称" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={form.control}
                        name={`education.data.${index}.time`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>时间</FormLabel>
                            <FormControl>
                              <Input placeholder="请输入时间" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <FormField
                        control={form.control}
                        name={`education.data.${index}.program`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>专业</FormLabel>
                            <FormControl>
                              <Input placeholder="请输入专业" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>

                    <div className="space-y-2">
                      <FormLabel>内容</FormLabel>
                      {form
                        .watch(`education.data.${index}.content`)
                        ?.map((_, contentIndex) => (
                          <div key={contentIndex} className="flex gap-2">
                            <FormField
                              control={form.control}
                              name={`education.data.${index}.content.${contentIndex}`}
                              render={({ field }) => (
                                <FormItem className="flex-1">
                                  <FormControl>
                                    <Input
                                      placeholder={`内容 ${contentIndex + 1}`}
                                      {...field}
                                    />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                            <Button
                              type="button"
                              variant="outline"
                              size="icon"
                              onClick={() => {
                                const currentContent = form.getValues(
                                  `education.data.${index}.content`
                                );
                                const newContent = currentContent.filter(
                                  (_, i) => i !== contentIndex
                                );
                                form.setValue(
                                  `education.data.${index}.content`,
                                  newContent
                                );
                              }}
                              className="h-9 w-9"
                            >
                              <ResumeIcon icon="ie-stick" size={14} />
                            </Button>
                          </div>
                        ))}
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => {
                          const currentContent =
                            form.getValues(`education.data.${index}.content`) ||
                            [];
                          form.setValue(`education.data.${index}.content`, [
                            ...currentContent,
                            "",
                          ]);
                        }}
                        className="w-full"
                      >
                        <ResumeIcon icon="plus" size={14} className="mr-2" />
                        添加内容
                      </Button>
                    </div>

                    <div className="flex justify-between">
                      <Button
                        type="button"
                        variant="outline"
                        onClick={() => removeEducation(index)}
                      >
                        <ResumeIcon
                          icon="ie-stick"
                          size={14}
                          className="mr-2"
                        />
                        删除教育经历
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              );
            })}

            <Button
              type="button"
              variant="outline"
              onClick={() =>
                appendEducation({
                  school: "",
                  time: "",
                  program: "",
                  content: [""],
                })
              }
              className="w-full"
            >
              <ResumeIcon icon="plus" size={16} className="mr-2" />
              添加教育经历
            </Button>
          </FormCard>

          {/* 工作经历 */}
          <FormCard title="工作经历">
            <FormField
              control={form.control}
              name="experience.title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>标题</FormLabel>
                  <FormControl>
                    <Input placeholder="请输入标题" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {experienceFields.map((item, index) => {
              const company = form
                .watch(`experience.data.${index}.company`)
                ?.trim();
              const role = form.watch(`experience.data.${index}.role`)?.trim();
              const title =
                [company, role].filter(Boolean).join(" / ") ||
                `工作经历 ${index + 1}`;

              return (
                <Card key={item.id} className="border-dashed">
                  <CardHeader>
                    <CardTitle className="text-base">{title}</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <FormField
                      control={form.control}
                      name={`experience.data.${index}.company`}
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>公司/项目</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="请输入公司或项目名称"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={form.control}
                        name={`experience.data.${index}.time`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>时间</FormLabel>
                            <FormControl>
                              <Input placeholder="请输入时间" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <FormField
                        control={form.control}
                        name={`experience.data.${index}.role`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>岗位/职责</FormLabel>
                            <FormControl>
                              <Input
                                placeholder="请输入岗位或职责"
                                {...field}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>

                    <div className="space-y-2">
                      <FormLabel>内容</FormLabel>
                      {form
                        .watch(`experience.data.${index}.content`)
                        ?.map((_, contentIndex) => (
                          <div key={contentIndex} className="flex gap-2">
                            <FormField
                              control={form.control}
                              name={`experience.data.${index}.content.${contentIndex}`}
                              render={({ field }) => (
                                <FormItem className="flex-1">
                                  <FormControl>
                                    <Input
                                      placeholder={`内容 ${contentIndex + 1}`}
                                      {...field}
                                    />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                            <Button
                              type="button"
                              variant="outline"
                              size="icon"
                              onClick={() => {
                                const currentContent = form.getValues(
                                  `experience.data.${index}.content`
                                );
                                const newContent = currentContent.filter(
                                  (_, i) => i !== contentIndex
                                );
                                form.setValue(
                                  `experience.data.${index}.content`,
                                  newContent
                                );
                              }}
                              className="h-9 w-9"
                            >
                              <ResumeIcon icon="ie-stick" size={14} />
                            </Button>
                          </div>
                        ))}
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => {
                          const currentContent =
                            form.getValues(
                              `experience.data.${index}.content`
                            ) || [];
                          form.setValue(`experience.data.${index}.content`, [
                            ...currentContent,
                            "",
                          ]);
                        }}
                        className="w-full"
                      >
                        <ResumeIcon icon="plus" size={14} className="mr-2" />
                        添加内容
                      </Button>
                    </div>

                    <div className="flex justify-between">
                      <Button
                        type="button"
                        variant="outline"
                        onClick={() => removeExperience(index)}
                      >
                        <ResumeIcon
                          icon="ie-stick"
                          size={14}
                          className="mr-2"
                        />
                        删除工作经历
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              );
            })}

            <Button
              type="button"
              variant="outline"
              onClick={() =>
                appendExperience({
                  company: "",
                  time: "",
                  role: "",
                  content: [""],
                })
              }
              className="w-full"
            >
              <ResumeIcon icon="plus" size={16} className="mr-2" />
              添加工作经历
            </Button>
          </FormCard>

          {/* 其他内容 */}
          {externalsFields.map((item, index) => (
            <FormCard
              key={item.id}
              title={
                form.watch(`externals.${index}.title`) ||
                `其他内容 ${index + 1}`
              }
            >
              <FormField
                control={form.control}
                name={`externals.${index}.title`}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>标题</FormLabel>
                    <FormControl>
                      <Input placeholder="请输入标题" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="space-y-2">
                <FormLabel>内容</FormLabel>
                {form
                  .watch(`externals.${index}.content`)
                  ?.map((_, contentIndex) => (
                    <div key={contentIndex} className="flex gap-2">
                      <FormField
                        control={form.control}
                        name={`externals.${index}.content.${contentIndex}`}
                        render={({ field }) => (
                          <FormItem className="flex-1">
                            <FormControl>
                              <Input
                                placeholder={`内容 ${contentIndex + 1}`}
                                {...field}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <Button
                        type="button"
                        variant="outline"
                        size="icon"
                        onClick={() => {
                          const currentContent = form.getValues(
                            `externals.${index}.content`
                          );
                          const newContent = currentContent.filter(
                            (_, i) => i !== contentIndex
                          );
                          form.setValue(
                            `externals.${index}.content`,
                            newContent
                          );
                        }}
                        className="h-9 w-9"
                      >
                        <ResumeIcon icon="ie-stick" size={14} />
                      </Button>
                    </div>
                  ))}
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    const currentContent =
                      form.getValues(`externals.${index}.content`) || [];
                    form.setValue(`externals.${index}.content`, [
                      ...currentContent,
                      "",
                    ]);
                  }}
                  className="w-full"
                >
                  <ResumeIcon icon="plus" size={14} className="mr-2" />
                  添加内容
                </Button>
              </div>

              <Button
                type="button"
                variant="outline"
                onClick={() => removeExternal(index)}
                className="w-full"
              >
                <ResumeIcon icon="ie-stick" size={14} className="mr-2" />
                删除此内容
              </Button>
            </FormCard>
          ))}

          <Button
            type="button"
            variant="outline"
            onClick={() => appendExternal({ title: "", content: [""] })}
            className="w-full"
          >
            <ResumeIcon icon="plus" size={16} className="mr-2" />
            添加其他内容
          </Button>

          <Button type="submit" className="w-full">
            保存简历
          </Button>
        </form>
      </Form>
    </div>
  );
}
